#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <unistd.h>
#include <memory>
#include <cstring>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "Log.hpp"
#include "InetAddr.hpp"

using namespace std;

const static int gbacklog = 8;
namespace socket_net
{
    class Socket;
    using sock_sptr = shared_ptr<Socket>;
    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR,
        USAGE_ERROR
    };

    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void BindSockOrDie(InetAddr &tranaddr) = 0;
        virtual void ListenSocketOrDie() = 0;
        virtual int Acceptaddr(InetAddr *tranaddr) = 0;
        virtual bool ConnetSocket(InetAddr &tranaddr) = 0;
        virtual int sockfd() = 0;
        virtual int Recv(string *out) = 0;
        virtual int Send(string &in) = 0;
        virtual void Close() = 0;
        virtual void SetSocketAddrReuse()=0;

    public:
        void BuildListenSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            SetSocketAddrReuse();
            BindSockOrDie(addr);
            ListenSocketOrDie();
        }
        bool BuildClientSocket(InetAddr &addr)
        {
            CreateSocketOrDie();
            return ConnetSocket(addr);
        }
    };
    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int fd = -1)
            : _sockfd(fd)
        {
        }
        void CreateSocketOrDie() override
        {
            // 1.创建套接字
            _sockfd = socket(AF_INET, SOCK_STREAM, 0); // 与udpserver不同
            if (_sockfd < 0)
            {

                Log(FATAL, "_sockfd create error!");
                exit(SOCKET_ERROR);
            }
            Log(DEBUG, "listensock create success! _sockfd:%d", _sockfd);
        }
        void BindSockOrDie(InetAddr &tranaddr) override
        {
            // 2. bind
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(tranaddr.port());
            local.sin_addr.s_addr = inet_addr(tranaddr.ip().c_str());

            int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                Log(FATAL, "bind error");
                exit(BIND_ERROR);
            }
            Log(DEBUG, "bind success, sockfd is : %d", _sockfd);
        }
        void ListenSocketOrDie() override
        {
            int n = ::listen(_sockfd, gbacklog);
            if (n < 0)
            {
                Log(FATAL, "listen error");
                exit(LISTEN_ERROR);
            }
            Log(DEBUG, "listen success, sockfd is : %d", _sockfd);
        }
        void SetSocketAddrReuse()
        {
            int opt=1;
    ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        }
        int Acceptaddr(InetAddr *tranaddr) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                cerr << strerror(sockfd) << endl;
                Log(WARNING, "accept error!  sockfd:%d", sockfd);
                sleep(1);
                return -1;
            }
            *tranaddr = peer;
            sock_sptr sock = make_shared<TcpSocket>(sockfd);
            return sockfd;
        }
        bool ConnetSocket(InetAddr &addr)
        {
            struct sockaddr_in server;
            // 构建目标主机的socket信息
            memset(&server, 0, sizeof(server));                    // 用来初始化
            server.sin_port = htons(addr.port());                  // 将网络地址转化为主机地址
            server.sin_addr.s_addr = inet_addr(addr.ip().c_str()); // ip地址
            server.sin_family = AF_INET;

            // 连接
            int n = connect(_sockfd, (sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                cout << "connet error! " << endl;
                return false;
            }
            return true;
        }
        int sockfd() override
        {
            return _sockfd;
        }
        int Recv(string *out) override
        {
                char inbuffer[4096];
                ssize_t n = ::recv(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
                if (n <= 0)
                {
                    cerr << "Recv error!" << endl;
                }
               if(n>0)
                {
                    //回显
                    inbuffer[n]=0;
                    *out=inbuffer;//每次重新加载缓冲区
                }
                return n;
        }
        int Send(string &in) override
        {
            int n=::send(_sockfd,in.c_str(),in.size(),0);
            return n;
        }
        void Close() override
        {
            ::close(_sockfd);
        }
    private:
        int _sockfd;
    };

}